package cn.ljlao.mall.ware.ware.service.impl;

import cn.ljlao.mall.ware.ware.feign.ProductFeign;
import cn.ljlao.mall.ware.ware.vo.SkuHasStockVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ljlao.common.utils.PageUtils;
import cn.ljlao.common.utils.Query;

import cn.ljlao.mall.ware.ware.dao.WareSkuDao;
import cn.ljlao.mall.ware.ware.entity.WareSkuEntity;
import cn.ljlao.mall.ware.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    ProductFeign productFeign;
    
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * skuId: 1
         * wareId: 1
         */

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStok(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> list = baseMapper.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId).eq("ware_id", wareId)
        );
        if (null==list ||list.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            Map<String, Object> skuInfo = (Map<String, Object>) productFeign.info(skuId).get("skuInfo");
            wareSkuEntity.setSkuName(skuInfo.get("skuName").toString());
            baseMapper.insert(wareSkuEntity);
        }
        baseMapper.addStok(skuId,wareId,skuNum);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId->{
            //返回结果集封装
            SkuHasStockVo vo = new SkuHasStockVo();
            Long count =  baseMapper.getSkuCount(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0); // 如果count 为null 那就是 false 没库存 反之 查库存
            return vo;
        }).collect(Collectors.toList());
    }

}